const JWT = require('../utils/jwt')
const Constant = require('../constant/constant')
const Common = require('../controller/common')

/**
 * token验证方法
 * @date 2021-03-18
 * @param {any} req
 * @param {any} res
 * @returns {boolean} true验证通过，false验证不通过
 */
function checkToken(req, res) {
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let token = req.headers.token
  let jwt = new JWT()
  //把token字符串解码成对象，如果token字符串不对或不存在，返回false
  let checkRes = jwt.verify(token)
  if (!checkRes) {
    resObj.msg = '请先登录'
    resObj.code = 403
    res.send(resObj)
    return false
  }
  let signTime = checkRes.iat
  let now = Math.floor(+new Date() / 1000)
  if (now - signTime > 86400) {
    resObj.msg = '请重新登录'
    resObj.code = 403
    res.send(resObj)
    return false
  }
  return true
}

exports.checkToken = checkToken
